﻿
using Coldairarrow.Business.Base_Manage;
using Coldairarrow.Entity.Base_leasesystem_car;
using Coldairarrow.Entity.Base_leasesystem_employee;
using Coldairarrow.Entity.Base_leasesystem_employeesign;
using Coldairarrow.Entity.Base_Leasesystem_equipment;
using Coldairarrow.Entity.Base_leasesystem_merchant;
using Coldairarrow.Entity.Base_leasesystem_transactionbatch;
using Coldairarrow.Entity.Base_leasesystem_transactionbatchsub;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.ViewModel;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_leasesystem_transactionbatch
{
    public class leasesystem_transactionbatchBusiness : BaseBusiness<leasesystem_transactionbatch>, Ileasesystem_transactionbatchBusiness, ITransientDependency
    {
        readonly IHomeBusiness _Home;
        public leasesystem_transactionbatchBusiness(IDbAccessor db,IHomeBusiness homeBusiness)
            : base(db)
        {
            _Home = homeBusiness;
        }

        #region 外部接口

        public async Task<object> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            //var where = LinqHelper.True<leasesystem_transactionbatch>();
            //var search = input.Search;

            //筛选
            //if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            //{
            //    var newWhere = DynamicExpressionParser.ParseLambda<leasesystem_transactionbatch, bool>(
            //        ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
            //    where = where.And(newWhere);
            //}

            var newData = q.Join(Db.GetIQueryable<leasesystem_merchant>(), a => a.MID, b => b.Id, (a, b) => new
            {
                a.BatchNo,
                b.customerName,
                a.CreateTime,
                a.TotalNum,
                a.TotalAmount,
                a.BusinesStatus
            });
            if (!input.Search.Keyword.IsNullOrEmpty()) {
                newData = newData.Where(a=>a.customerName.Contains(input.Search.Keyword));
            }

            var res = new { 
                Data = newData.Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows),
                Total = newData.Count()
            };

            return res;
        }

        public async Task<leasesystem_transactionbatch> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(leasesystem_transactionbatch data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(leasesystem_transactionbatch data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<object> SettlementExcel(DataTable dt, string userid)
        {
            List<DataTableHelp> list = new List<DataTableHelp>();
            bool istrue = true;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataTableHelp help = new DataTableHelp();

                if (dt.Rows[i][0].ToString().IsNullOrEmpty())
                {
                    DataTableHelp help1 = ReadSettlementHelp(dt, i, "姓名", true, "");
                    list.Add(help1);
                    istrue = false;
                    continue;
                }
                else if (dt.Rows[i][1].ToString().IsNullOrEmpty())
                {
                    DataTableHelp help1 = ReadSettlementHelp(dt, i, "身份证", true, "");
                    list.Add(help1);
                    istrue = false;
                    continue;
                }
                else if (dt.Rows[i][2].ToString().IsNullOrEmpty())
                {
                    DataTableHelp help1 = ReadSettlementHelp(dt, i, "联系电话", true, "");
                    list.Add(help1);
                    istrue = false;
                    continue;
                }
                else if (dt.Rows[i][5].ToString().IsNullOrEmpty())
                {
                    DataTableHelp help1 = ReadSettlementHelp(dt, i, "租金", true, "");
                    list.Add(help1);
                    istrue = false;
                    continue;
                }
                else
                {
                    //根据身份证号码查询出租人表数据
                    var obj =await Db.GetIQueryable<leasesystem_employee>().Where(a => a.IdCardNo == dt.Rows[i][1].ToString()).FirstOrDefaultAsync();
                    if (obj == null)
                    {
                        DataTableHelp help1 = ReadSettlementHelp(dt, i, "", false, "查无此人！");
                        list.Add(help1);
                        istrue = false;
                        continue;
                    }
                    else
                    {
                        if (obj.AuditInf != 1)
                        {
                            DataTableHelp help1 = ReadSettlementHelp(dt, i, "", false, "未完成实名认证");
                            list.Add(help1);
                            istrue = false;
                            continue;
                        }
                        else {
                            var user = await  Db.GetIQueryable<Base_User>().Where(a => a.Id == userid).FirstOrDefaultAsync();
                            if (user.brandId == obj.Id) {
                                DataTableHelp help1 = ReadSettlementHelp(dt, i, "", false, "该出租人非本企业人员");
                                list.Add(help1);
                                istrue = false;
                                continue;
                            }
                            else
                            {
                                var empsign = await  Db.GetIQueryable<leasesystem_employeesign>().Where(a => a.employeeId == obj.Id).FirstOrDefaultAsync();
                                if (empsign == null)
                                {
                                    DataTableHelp help1 = ReadSettlementHelp(dt, i, "", false, "该出租人未与服务商签约");
                                    list.Add(help1);
                                    istrue = false;
                                    continue;
                                }
                                else {
                                    var carinfo = await  Db.GetIQueryable<leasesystem_car>().Where(a => a.Status == 1).ToListAsync();//审核通过的数据
                                    var deviceinfo = await  Db.GetIQueryable<leasesystem_equipment>().Where(a => a.Status == 1).ToListAsync();
                                    if (carinfo.Count() <= 0 || deviceinfo.Count() <= 0)
                                    {
                                        DataTableHelp help1 = ReadSettlementHelp(dt, i, "", false, "车辆或设备未有出租的");
                                        list.Add(help1);
                                        istrue = false;
                                        continue;
                                    }
                                    else {
                                        
                                        //if (_Home.) { 
                                        
                                        //}
                                        DataTableHelp help1 = ReadSettlementHelp(dt, i, "", false, "信息完整，符合导入要求");
                                        list.Add(help1);
                                    }
                                }
                            }
                        }
                    }

                }

            }
            var result = new { 
                Total = list.Count(),
                Data = list,
                istrue = istrue
            };
            return result;
        }

        public async Task AddListAsync(List<DataTableHelp> data,string guid,string userid)
        {
            List<leasesystem_transactionbatchsub> batchsubList = new List<leasesystem_transactionbatchsub>();

            var emp =await  Db.GetIQueryable<leasesystem_employee>().Where(a => a.IdCardNo == data[0].IdNumber).FirstOrDefaultAsync();
            var merchant = Db.GetIQueryable<leasesystem_merchant>().Where(a => a.Id == emp.MID).FirstOrDefault();
            var service = Db.GetIQueryable<leasesystem_employeesign>().Where(a => a.employeeId == emp.Id).FirstOrDefault();
            leasesystem_transactionbatch batch = new leasesystem_transactionbatch();
            batch.Id = IdHelper.GetId();
            batch.CreateTime = DateTime.Now;
            batch.CreatorId = userid;
            batch.MID = merchant.Id;
            batch.ServiceProviderId = service.ServiceID;
            batch.ServiceProviderName = service.ServiceName;
            batch.BatchStatus = 1;
            batch.BatchNo = IdHelper.GetId();
            batch.TotalNum = data.Count;
            batch.TotalAmount = data.Sum(a=>a.Rental);
            
            batch.BusinesStatus = 1;
            batch.resJson = "";
            batch.RechargeRate = "13";

            for (int i = 0; i < data.Count; i++)
            {
                leasesystem_transactionbatchsub batchsub = new leasesystem_transactionbatchsub();
                
                batchsub.Id = IdHelper.GetId();
                batchsub.CreateTime = DateTime.Now;
                batchsub.CreatorId = userid;
                batchsub.TBID = batch.Id;
                batchsub.PaymentOutBatchNo = "POBN" + IdHelper.GetId();
                batchsub.PaymentOutOrderNo = "POON" + IdHelper.GetId();
                batchsub.PaymentOutAmount = data[i].Rental;
                batchsub.BeneficiaryName = data[i].Name;
                batchsub.BeneficiaryAccountNumber = data[i].BankAcc;
                batchsub.idCardNo = data[i].IdNumber;
                batchsub.employeeId = emp.Id;
                batchsub.BankName = data[i].BankName;
                batchsub.ordrId = "Ord" + IdHelper.GetId();
                batchsub.Description = data[i].Remark;
                batchsub.sendsmsstatus = 1;
                batchsubList.Add(batchsub);
            }
            await  InsertAsync(batch);
            await  Db.InsertAsync(batchsubList);
        }


        #endregion

        #region 私有成员

        #endregion

        /// <summary>
        /// 读取excel 返回信息辅助
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="index"></param>
        /// <param name="note"></param>
        /// <param name="istrue"></param>
        /// <param name="other"></param>
        /// <returns></returns>
        public DataTableHelp ReadSettlementHelp(DataTable dt, int index, string note, bool istrue, string other)
        {
            DataTableHelp help = new DataTableHelp();

            help.Name = dt.Rows[index][0].ToString();
            help.IdNumber = dt.Rows[index][1].ToString();
            help.Phone = dt.Rows[index][2].ToString();
            help.BankAcc = dt.Rows[index][3].ToString();
            help.BankName = dt.Rows[index][4].ToString();
            if (!dt.Rows[index][5].ToString().IsNullOrEmpty())
            {
                help.Rental = decimal.Parse(dt.Rows[index][5].ToString());
            }

            help.Remark = dt.Rows[index][6].ToString();
            if (istrue)
            {
                help.result = note + "信息未填写";
            }
            else
            {
                help.result = other;
            }

            return help;
        }
    }
}